package com.hyacinth.forumbite.interceptor;

import com.hyacinth.forumbite.common.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author: Yun
 * @Date: 2025/5/21
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${bit-forum.login.url}")
    private String url;

    /**
     * 前置处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
            if (!url.startsWith("/")) {
                url = "/" + url;
                response.sendRedirect(url);
            }
            log.info("已拦截未登录用户请求");
            return false;
        }
        return true;
    }
}
